/**
 * 使用storage将ref缓存到本地
 * 相较与vue-use不同的是：storage到ref的操作只有created的时候才执行（vue-use是storage改变就会同步）
 * @param key 唯一key
 * @param defaultValue 默认值
 * @param config 配置 （store
 * @returns REF
 */
export const useStorageX = (
  key: string,
  defaultValue: any,
  config?: {
    storage?: { setItem: (key: string, value: any) => {}; getItem: (key: string) => string }
  },
) => {
  const value = ref('')

  const { storage = window.localStorage } = config || {}

  try {
    value.value = JSON.parse(storage.getItem(key) || '')
  } catch (error) {
    value.value = defaultValue
  }

  const storageValue = computed({
    get() {
      return value.value
    },
    set(v: any) {
      storage.setItem(key, JSON.stringify(v))
      value.value = v
    },
  })

  return storageValue
}
